package influxdb

import (
	"context"
	"fmt"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
	"time"
)

type InfluxDBClient struct {
	client influxdb2.Client
}

type Record struct {
	Measurement string
	Tags map[string]string
	Fields map[string]interface{}
}

func New(addr string) (c *InfluxDBClient) {
	// Create a new client using an InfluxDB server base URL and an authentication token
	c=&InfluxDBClient{client: influxdb2.NewClient(addr, "")}
	return c
}

func (c *InfluxDBClient) Write(r *Record,org string,bucket string) (err error) {
	writer:=c.client.WriteAPIBlocking(org,bucket)
	p:=influxdb2.NewPoint(r.Measurement,r.Tags,r.Fields,time.Now())
	err=writer.WritePoint(context.Background(),p)

	return err
}

func (c *InfluxDBClient) Query(measurement string,org string,bucket string) (r []*Record,err error){
	reader:=c.client.QueryAPI(org)
	result,err:=reader.Query(context.Background(),fmt.Sprintf(`from(bucket:"%s")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "%s")`,bucket,measurement))
	if err!=nil{
		return nil, err
	}
	if err == nil {
		// Use Next() to iterate over query result lines
		for result.Next() {
			// Observe when there is new grouping key producing new table
			if result.TableChanged() {
				fmt.Printf("table: %s\n", result.TableMetadata().String())
			}
			// read result
			fmt.Printf("row: %s\n", result.Record().String())
			r = append(r, &Record{
				Measurement: result.Record().Measurement(),
				Fields:      result.Record().Values(),
			})
		}
		if result.Err() != nil {
			fmt.Printf("Query error: %s\n", result.Err().Error())
			return nil,result.Err()
		}
	}
	return
}
